package com.runnor.common.websys.system.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.runnor.common.websys.system.entity.User;
import com.runnor.common.websys.system.mapper.SysRoleMapper;
import com.runnor.common.websys.system.mapper.UserMapper;
import com.runnor.common.websys.system.security.LoginUser;
import com.runnor.common.websys.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author runnor-yh
 * @date 2023年08月15日 14:41
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {
    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    UserMapper userMapper;

    @Override
    public List getUserAuthority(String userId) {
        return sysRoleMapper.listPermissionByUserId(userId);
    }

    @Override
    public Page pages(Page page, QueryWrapper<User> queryWrapper) {
        return userMapper.pages(page, queryWrapper);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("id,username,password").lambda()
                .eq(User::getUsername, username)
                .eq(User::getEnabled, true)
                .eq(User::getDeleted, false)
                .last("limit 1");
        User user = this.baseMapper.selectOne(wrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        List userAuthority = AuthorityUtils.commaSeparatedStringToAuthorityList(ArrayUtil.join(getUserAuthority(user.getId()).toArray(), ","));
        LoginUser loginUser = new LoginUser(user.getId(), user.getUsername(), user.getPassword(), userAuthority);
        return loginUser;

    }
}
